package org.lanqiao.service.impl;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.lanqiao.information.IAskService;
import org.lanqiao.mapper.AskMapper;
import org.lanqiao.information.Ask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service(interfaceClass = IAskService.class, timeout = 5000)
public class AskServiceImpl implements IAskService {

    @Autowired
    AskMapper askMapper;


    @Override
    public void changeStatus(Integer askId, Integer status) {
        Ask ask  = new Ask();
        ask.setAskId(askId);
        ask.setStatus(status);
        askMapper.updateById(ask);
    }

    @Override
    public IPage<Ask> pageListByUserId(Integer pageNum, Integer pageSize, Map<String, String> queryMap) {
        QueryWrapper<Ask> queryWrapper = queryWrapper1(queryMap);
        IPage<Ask> page = new Page<>(pageNum, pageSize, true);
        IPage<Ask> askIPage = askMapper.selectPage(page, queryWrapper);
        for (Ask record : askIPage.getRecords()) {
            if (record.getLikedIds() == null) {
                record.setLikedIds("");
            }
            if (Arrays.asList(record.getLikedIds().split(", ")).contains(queryMap.get("userId") + "")) {
                record.setIsLike(1);
            } else {
                record.setIsLike(0);
            }
        }
        return askIPage;
    }

    @Override
    public void add(Ask ask) {
        askMapper.insert(ask);
    }

    @Override
    public void logicallyDelete(Integer askId) {
        // 逻辑删除 将status设置为3
        Ask ask = new Ask();
        ask.setAskId(askId);
        ask.setStatus(4);
        askMapper.updateById(ask);
    }

    @Override
    public void physicallyDelete(Integer askId) {
        // 物理删除 删除数据库中的实体
        askMapper.deleteById(askId);
    }

    @Override
    public void update(Ask ask) {
        ask.setUpdateTime(new Date());
        askMapper.updateById(ask);
    }

    @Override
    @Transactional
    public Ask findAskById(Integer askId) {
        Ask ask = askMapper.selectById(askId);
        ask.setViewCount(ask.getViewCount() + 1);
        askMapper.updateById(ask);
        return ask;
    }
    @Override
    public List<Ask> findAll() {
        List<Ask> asks = askMapper.selectList(null);
        return asks;
    }

    @Override
    public List<Ask> findList(Map queryMap) {
        QueryWrapper queryWrapper = queryWrapper(queryMap);
        List<Ask> askList = askMapper.selectList(queryWrapper);
        if (queryMap.get("userId") != null) {
            Integer userId = Integer.valueOf(String.valueOf(queryMap.get("userId")));
            for (Ask ask : askList) {
                if (ask.getLikedIds() == null) {
                    ask.setLikedIds("");
                }
                if (Arrays.asList(ask.getLikedIds().split(", ")).contains(userId + "")) {
                    ask.setIsLike(1);
                } else {
                    ask.setIsLike(0);
                }
            }
        }
        return askList;
    }


    @Override
    public void toggleLike(Map map) {
        // 获取用户userId
        Integer userId = Integer.parseInt(String.valueOf(map.get("userId")));
        // 获取回答askId
        Integer askId = Integer.parseInt(String.valueOf(map.get("askId")));
        // 根据回答askId查找实体
        Ask ask = askMapper.selectById(askId);
        // 获取所有点赞用户userIds
        String userIds = ask.getLikedIds();
        if (userIds == null) {
            userIds = "";
        }
        // 转换为List列表
        List<String> tempList = Arrays.asList(userIds.split(", "));
        List<String> list = new ArrayList<>(tempList);
        // 遍历查找用户的userId，观察是否用户已经存在用户id
        if (list.contains(userId + "")) {
            // 存在 则移除
            list.remove(userId + "");
            // 减少一个赞
            ask.setLikedCount(ask.getLikedCount() - 1);
        } else {
            // 不存在 则增加
            list.add(userId + "");
            // 增加一个赞
            ask.setLikedCount(ask.getLikedCount() + 1);
        }
        // 去除所有空字符串
        list = list.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
        String[] tempArr = new String[list.size()];
        // 将集合转换为数组
        String[] array = list.toArray(tempArr);
        // 使用工具类将数组转换为字符串
        String ids = StringUtils.join(array, ", ");


        askMapper.updateById(ask);
    }

    @Override
    public void informFail(Integer askId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("ask_id", askId);
        Ask ask = new Ask();
        ask.setAskId(askId);
        ask.setInformContent("");
        ask.setInformUserId(null);
        ask.setStatus(1);
        askMapper.updateById(ask);
    }

    @Override
    public void informSuccess(Integer askId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("ask_id", askId);
        Ask ask = new Ask();
        ask.setAskId(askId);
        ask.setStatus(4);
        askMapper.updateById(ask);
    }


    @Override
    public IPage<Ask> pageList(Integer pageNum, Integer pageSize, Map queryMap) {
        QueryWrapper<Ask> queryWrapper = queryWrapper(queryMap);
        IPage<Ask> page = new Page<>(pageNum, pageSize, true);

        IPage<Ask> askIPage = askMapper.selectPage(page, queryWrapper);
        if (queryMap.get("userId") != null) {
            Integer userId = Integer.valueOf(String.valueOf(queryMap.get("userId")));
//            queryWrapper.eq("user_id", userId);
            askIPage = askMapper.selectPage(page, queryWrapper);
            for (Ask record : askIPage.getRecords()) {
                if (record.getLikedIds() == null) {
                    record.setLikedIds("");
                }
                if (Arrays.asList(record.getLikedIds().split(", ")).contains(userId + "")) {
                    record.setIsLike(1);
                } else {
                    record.setIsLike(0);
                }
            }
        }
        return askIPage;
    }

    @Override
    public IPage<Ask> pageAll(Integer pageNum, Integer pageSize) {
        Page<Ask> page = new Page<>(pageNum, pageSize);
        Page<Ask> askPage = askMapper.selectPage(page, null);
        return askPage;

    }


    @Override
    public IPage<Ask> pageAll(Integer pageNum, Integer pageSize, Integer userId) {
        Page<Ask> page = new Page<>(pageNum, pageSize);
        Page<Ask> askPage = askMapper.selectPage(page, null);
        List<Ask> askList = askPage.getRecords();
        for (Ask ask : askList) {
            if (Arrays.asList(ask.getLikedIds().split(", ")).contains(userId + "")) {
                ask.setIsLike(1);
            } else {
                ask.setIsLike(0);
            }
        }
        return askPage;

    }

    @Override
    public void inform(Map informMap) {
        Integer askId = Integer.parseInt(String.valueOf(informMap.get("askId")));
        Integer informUserId = Integer.parseInt(String.valueOf(informMap.get("informUserId")));
        String informContent = (String) informMap.get("informContent");
        if (askId == null || informContent == null || informUserId == null) {
            throw new RuntimeException("缺少举报条件");
        }
        Ask ask = new Ask();
        ask.setAskId(askId);
        ask.setInformUserId(informUserId);
        ask.setInformContent(informContent);
        // 状态为3被举报
        ask.setStatus(3);
        askMapper.updateById(ask);
    }

    private QueryWrapper<Ask> queryWrapper(Map<String,String> queryMap){
        // 查询条件
        QueryWrapper<Ask> queryWrapper = null;
        if(queryMap !=null){
            queryWrapper = new QueryWrapper<>();
            if(!StringUtils.isEmpty(queryMap.get("askId"))){
                queryWrapper.eq("askId",queryMap.get("askId"));
            }
            if(!StringUtils.isEmpty(queryMap.get("title"))){
                queryWrapper.like("title",queryMap.get("title"));
            }
            if(!StringUtils.isEmpty(queryMap.get("content"))){
                queryWrapper.like("content",queryMap.get("content"));
            }
            if(!StringUtils.isEmpty(queryMap.get("status"))){
                queryWrapper.eq("status",queryMap.get("status"));
            }
            if(!StringUtils.isEmpty(queryMap.get("informUserId"))){
                queryWrapper.eq("inform_user_id",queryMap.get("informUserId"));
            }
//            if(!StringUtils.isEmpty(queryMap.get("userId"))){
//                queryWrapper.eq("user_id",queryMap.get("userId"));
//            }
            if(!StringUtils.isEmpty(queryMap.get("orderby"))){
                queryWrapper.orderByDesc(new String[] {(String) queryMap.get("orderby")});
            }
        }
        return  queryWrapper;
    }

    private QueryWrapper<Ask> queryWrapper1(Map<String,String> queryMap){
        // 查询条件
        QueryWrapper<Ask> queryWrapper = null;
        if(queryMap !=null){
            queryWrapper = new QueryWrapper<>();
            if(!StringUtils.isEmpty(queryMap.get("askId"))){
                queryWrapper.eq("askId",queryMap.get("askId"));
            }
            if(!StringUtils.isEmpty(queryMap.get("title"))){
                queryWrapper.like("title",queryMap.get("title"));
            }
            if(!StringUtils.isEmpty(queryMap.get("content"))){
                queryWrapper.like("content",queryMap.get("content"));
            }
            if(!StringUtils.isEmpty(queryMap.get("status"))){
                queryWrapper.eq("status",queryMap.get("status"));
            }
            if(!StringUtils.isEmpty(queryMap.get("informUserId"))){
                queryWrapper.eq("inform_user_id",queryMap.get("informUserId"));
            }
            if(!StringUtils.isEmpty(queryMap.get("userId"))){
                queryWrapper.eq("user_id",queryMap.get("userId"));
            }
            if(!StringUtils.isEmpty(queryMap.get("orderby"))){
                queryWrapper.orderByDesc(new String[] { queryMap.get("orderby")});
            }
        }
        return  queryWrapper;
    }
}
